<template>
  <div>
    <!-- 用户名：<input type="text">
    <br>
    密码：<input type="password">
    <br>
    <input type="button" value="登录"> -->
    <div>
      <h2>登录</h2>
    </div>
    <el-form :rules="rules" ref="rulesform" :model="logindata">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="logindata.username" type="text"></el-input>
      </el-form-item>
      <el-form-item label="密码">
        <el-input v-model="logindata.password" type="password"></el-input>
      </el-form-item>
    </el-form>
    <el-button type="primary" plain @click="updata">登录</el-button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      logindata: {
        username: "admin",
        password: "123456",
      },

      rules: {
        username: [
          { required: true, message: "请输入活动名称", trigger: "blur" },
          { min: 3, max: 5, message: "长度在 3 到 5 个字符", trigger: "blur" },
        ],
      },
    };
  },
  methods: {
    //先进行表单验证，如果正确就发起请求，如果不正确，就执行错误语句(提示)
    updata() {
      this.$refs.rulesform.validate((valid, backvalid) => {
        if (valid) {
          //表单正确，就发起请求，传入参数
          this.$qiuzi.post("/login", this.logindata).then((res) => {
            console.log(res);
            const { data, meta } = res.data;
            if (meta.status == 400) {
              //状态为400是失败
              this.$message.error("你脑子被驴踢了，登录失败了");
            } else if (meta.status == 200) {
              //状态为200是登录成功
              //将用户的数据通过  mutation 触发 userchange 方法 (事件)
              //保存到数据仓库中
              this.$store.commit("userchange", data);
              //设置弹窗
              this.$message({
                type: "success",
                message: "登录成功啦，宝贝",
              });
              //登录成功跳转页面
              this.$router.push({ path: "/home" });
            }
          });
        } else {
          this.$message.error("您的表单填写有误");
          return false;
        }
      });
    },
  },
};
</script>

<style>
</style>
